const express = require('express')

const app = express()

const joi = require('joi')

// // 设置允许跨域访问该服务
// app.all('*', function (req, res, next) {
//     res.header("Access-Control-Allow_Origin", "*");
//     res.header("Access-Control-Allow_Origin", "PUT,GET,POST,DELETE,OPTIONS");
//     res.header("Access-Control-Allow_Origin", "X-Requested-With");
//     res.header("Access-Control-Allow_Origin", "Content-Type");
//     res.header("Access-Control-Allow_Origin", "ContentType");
//     next();
// })

//托管静态资源路径
app.use(express.static('./dist'))


// 结局跨域问题
const cors = require('cors')
app.use(cors())

// //引入上传文件multer
// const upload = require('./router/upload')
// app.use("/api/upload", upload)

//解析表单提交过来的
// @ts-ignore
app.use(express.urlencoded({ extends: false }))


// 封装一个处理函数，让处理错误信息简化
app.use(function (req, res, next) {
    // @ts-ignore
    res.cc = function (err, status = 1) {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

// 配置解析token的中间件
const expressJwt = require('express-jwt')
const config = require('./config')
// @ts-ignore
app.use(expressJwt({ secret: config.jwtSecretKey }).unless({ path: [/^\/api/] }))

// 导入user路由模块
const urouter = require('./router/user')
app.use('/api', urouter)

//导入userinfo路由模块
const userinfoRouter = require('./router/userinfo')
app.use('/my', userinfoRouter)

//导入teacher模块
const teacher = require('./router/teacher')
app.use('/teacher', teacher)

//导入系管理员模块
const minAdmin = require('./router/minAdmin')
app.use('/minAdmin', minAdmin)

//导入学院管理员模块
const bigAdmin = require('./router/bigAdmin')
app.use('/bigAdmin', bigAdmin)

// 路由之后错误中间件
app.use(function (err, req, res, next) {
    if (err instanceof joi.ValidationError) return res.cc(err)
    if (err.name === 'UnauthorizedError') return res.cc('身份没有通过验证')
    // 未知的错误
    res.send(err)
})

// 启动服务器
app.listen(8080, function () {
    console.log('http://127.0.0.1:8080')
})